<template>
  <page-card title="用户扩展"
             :sub-title="!this.$route.query.id ? '新增':'编辑'"
             :need-back="true">

    <a-form :form="form"
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol">
      <a-form-item label="ID"
                   v-show="false">
        <a-input v-decorator="['id']" />
      </a-form-item>
      <a-form-item label="字段名称">
        <a-input allowClear
                 placeholder="请输入字段名称"
                 :maxLength="10"
                 v-decorator="['columnsName', {
                   rules: [{
                     required: true, transform: value => value ? value.trim() : '', message: '请输入字段名称'
                   }]
                 }]" />
      </a-form-item>
      <a-form-item label="字段值">
        <a-input allowClear
                 addon-before="extend_"
                 :disabled="extendId&&extendId.length>0"
                 placeholder="请输入字段值,仅支持英文字符"
                 :maxLength="20"
                 v-decorator="['columnsValue', {
                   rules: [{
                     required: true, pattern:/^[a-zA-Z]+$/, message: '请输入字段值,仅支持英文字符'
                   },{
                     min: 1, max: 20, message: '长度在1到20个字符', trigger: 'blur'
                   }]
                 }]" />
      </a-form-item>
      <a-form-item label="字段类型"
                   required>
        <a-select default-value="1"
                  :disabled="extendId&&extendId.length>0"
                  v-model="columnsType"
                  style="width: 100%">
          <a-select-option value="1">
            文本框
          </a-select-option>
          <a-select-option value="2">
            下拉列表
          </a-select-option>
          <a-select-option value="3">
            单选框
          </a-select-option>
          <a-select-option value="4">
            时间组件
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="数据源"
                   v-if="columnsType==2||columnsType==3">
        <a-row class="header"
               style="background: #fafafa;">
          <a-col :span="4">
            <a-tooltip title="选项显示文本"
                       :mouseEnterDelay="0.3">
              <span>文本</span>
            </a-tooltip>
          </a-col>
          <a-col :span="1">

          </a-col>
          <a-col :span="4">
            <a-tooltip title="选项隐藏值"
                       :mouseEnterDelay="0.3">
              <span>值</span>
            </a-tooltip>
          </a-col>
          <a-col :span="3"
                 style="text-align: center;">操作</a-col>
        </a-row>
        <a-row v-for="(option, $index) in list.optionList"
               :key="$index"
               class="option">
          <a-col :span="4">
            <a-input v-model="option.label"
                     @blur="checkLabel(option, $index)"></a-input>
          </a-col>
          <a-col :span="1">

          </a-col>
          <a-col :span="4">
            <a-input v-model="option.value"
                     @blur="checkValue(option, $index)"></a-input>
          </a-col>
          <a-col :span="3"
                 style="text-align: center;">
            <a-icon type="plus-circle"
                    class="distance"
                    @click="addOption($index)" />
            <a-icon type="minus-circle"
                    @click="removeOption($index)" />
          </a-col>
        </a-row>
      </a-form-item>
      <a-form-item label="是否必填">
        <ZSwitchOneZero checked-children="是"
                        un-checked-children="否"
                        v-model="isNull" />
      </a-form-item>
      <a-form-item label="是否可修改">
        <ZSwitchOneZero checked-children="是"
                        un-checked-children="否"
                        v-model="isUpdate" />
      </a-form-item>
      <a-form-item label="是否唯一">
        <ZSwitchOneZero checked-children="是"
                        un-checked-children="否"
                        v-model="isUnique" />
      </a-form-item>
      <a-form-item label="状态">
        <a-radio-group v-decorator="['status', {
                         initialValue: '1'
                       }]"
                       :options="typeOptions" />
      </a-form-item>
      <a-form-item label="描述">
        <a-textarea :maxLength="200"
                    placeholder="请输入描述"
                    v-decorator="['remark']"
                    style="resize:none; height:150px"></a-textarea>
      </a-form-item>
    </a-form>

    <a-form-item label=" "
                 :colon="false">
      <div style="text-align:center">
        <a-button type="primary"
                  action
                  @click="handleSave">保存</a-button>
      </div>
    </a-form-item>
  </page-card>
</template>

<script>

import { saveOrUpdateUserExtend, getUserExtendById } from '../../api/user/extend'
const cloneDeep = require('clone')
export default {
  data () {
    return {
      list: {
        optionList: [
          { label: '选项1', value: '1' },
          { label: '选项2', value: '2' },
          { label: '选项3', value: '3' }
        ]
      },
      extendId: '',
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 }
      },
      typeOptions: [{
        label: '启用',
        value: '1'
      }, {
        label: '禁用',
        value: '0'
      }],
      columnsType: '1',
      isNull: '0',
      isUpdate: '0',
      isUnique: '0',
      data: [],
      form: this.$form.createForm(this)
    }
  },
  mounted () {
    const id = this.$route.query.id
    this.extendId = id
    if (id) {
      this.getById(id)
    }
  },
  methods: {
    // 判读当前选项输入的lable值是否重复
    checkLabel: function (option, index) {
      // 需要当前有数据的
      if (option.label) {
        const idx = this.list.optionList.findIndex(item => {
          return item.label == option.label
        })
        idx != -1 && idx != index && this.message.warning(`当前文本${option.label}和 第${idx + 1}项的“${option.label}” 相等，请更改！`)
        return
      }
    },
    // 判读当前选项输入的text值是否重复
    checkValue: function (option, index) {
      // 需要当前有数据的
      if (option.value) {
        const idx = this.list.optionList.findIndex(item => {
          return item.value == option.value
        })
        idx != -1 && idx != index && this.message.warning(`当前值${option.value}和 第${idx + 1}项的“${option.value}” 相等，请更改！`)
        return
      }
    },
    // 新增选项
    addOption (index) {
      let optionList = cloneDeep(this.list.optionList)
      optionList.splice(index + 1, 0, { label: '', value: '', checked: false })
      this.$set(this.list, 'optionList', optionList)
    },
    // 移除选项
    removeOption (index) {
      let optionList = cloneDeep(this.list.optionList)
      optionList.splice(index, 1)
      if (optionList.length == 0) {
        this.$set(this.list, 'optionList', [{ label: '', value: '' }])
      } else {
        this.$set(this.list, 'optionList', optionList)
      }
    },
    getById (id) {
      getUserExtendById(id).then((response) => {
        const values = {}
        for (const k in this.form.fieldsStore.fieldsMeta) {
          // eslint-disable-next-line no-prototype-builtins
          response.hasOwnProperty(k) && (values[k] = response[k])
        }
        values.columnsValue = values.columnsValue.substring(7, values.columnsValue.length)
        this.form.setFieldsValue(values)
        this.columnsType = response.columnsType
        this.isNull = response.isNull
        this.isUpdate = response.isUpdate
        this.isUnique = response.isUnique
        if (response.source) {
          this.list.optionList = eval(response.source)
        }
      })
    },
    handleSave () {
      this.form.validateFieldsAndScroll((err, values) => {
        if (err) {
          return
        }
        if (values.columnsName) {
          values.columnsName = values.columnsName.trim()
        }
        values.columnsValue = 'extend_' + values.columnsValue
        values.columnsType = this.columnsType
        values.isNull = this.isNull
        values.isUpdate = this.isUpdate
        values.isUnique = this.isUnique
        let opts = this.list.optionList
        if (values.columnsType === '2' || values.columnsType === '3') {
          let newTxtList = []
          let txtMap = new Map()
          opts.map(item => {
            if (!txtMap.has(item.label)) {
              txtMap.set(item.label, true)
            } else {
              newTxtList.push(item)
            }
          })
          if (newTxtList.length > 0) {
            return this.message.warning(`数据源文本出现重复数据，请更改后提交！`)
          }

          let newValList = []
          let valMap = new Map()
          opts.map(item => {
            if (!valMap.has(item.value)) {
              valMap.set(item.value, true)
            } else {
              newValList.push(item)
            }
          })
          if (newValList.length > 0) {
            return this.message.warning(`数据源参数值出现重复数据，请更改后提交！`)
          }
        }
        values.source = opts
        saveOrUpdateUserExtend(values).then((response) => {
          this.$router.go(-1)
        })
      })
    }
  }
}
</script>
<style lang="less" scoped>
::v-deep .ant-modal-body {
  padding: 20px 40px !important;
  .header {
    background: #fafafa;
    display: flex;
    justify-content: space-between;
    line-height: 45px;
    > div {
      text-align: center;
    }
  }
  .option {
    display: flex;
    justify-content: space-between;
    line-height: 45px;
    border-bottom: 1px solid #e8e8e8;
    padding: 10px 0;
    .advanced {
      cursor: pointer;
      padding: 0 10px;
      color: #1890ff;
    }
  }
}
.data-box {
  height: 62px;
  line-height: 32px;
}
.distance {
  margin-right: 10px;
}
</style>